'use strict';

const { Service } = require('egg');
const COS = require('cos-nodejs-sdk-v5');
const { cos_1043829026 } = require('../../config/kujomiva/account.config')();

function cutCosName(fileName) {
    return fileName.slice(fileName.indexOf('myqcloud.com/') + 'myqcloud.com/'.length);
}

class KujoMiva extends Service {
    // 上传文件
    async putObject(options) {
        const { ctx, app } = this;
        const { fileBody, fileName, BucketName } = options;
        const nsp = app.io.of('/api');
        const cos = new COS({ ...cos_1043829026.account });
        const putObject = await app.promisify(cos.putObject, cos);
        const suffix = fileName.slice(fileName.lastIndexOf('.'));

        return await putObject({
            Bucket: `${BucketName}-${cos_1043829026.appid}`,
            Region: 'ap-chengdu',
            Key: app.md5(JSON.stringify(fileBody)) + suffix,
            Body: fileBody,
            onProgress(progressData) {
                console.log(progressData);
                nsp.to(app.md5(ctx.request.token)).emit('progressCOS', {
                    fileName,
                    progressData
                });
            }
        }).then(res => {
            return res;
        }).catch(err => {
            return err;
        });
    }
    // 删除文件
    async deleteObject(options) {
        const { app } = this;
        const { fileName, BucketName } = options;
        const cos = new COS({ ...cos_1043829026.account });
        const deleteObject = await app.promisify(cos.deleteObject, cos);
        const Key = cutCosName(fileName);
        return await deleteObject({
            Bucket: `${BucketName}-${cos_1043829026.appid}`,
            Region: 'ap-chengdu',
            Key
        }).then(res => {
            return res;
        }).catch(err => {
            return err;
        });
    }
    // 批量删除文件
    async deleteMultipleObject(options) {
        const { app } = this;
        const { fileNameArray, BucketName } = options;
        const cos = new COS({ ...cos_1043829026.account });
        const deleteMultipleObject = await app.promisify(cos.deleteMultipleObject, cos);

        for (let i = 0; i < fileNameArray.length; i++) {
            fileNameArray[i].Key = cutCosName(fileNameArray[i].Key);
        }

        const params = {
            Bucket: `${BucketName}-${cos_1043829026.appid}`,
            Region: 'ap-chengdu',
            Objects: fileNameArray
        };

        return await deleteMultipleObject(params)
            .then(res => {
                return res;
            }).catch(err => {
                return err;
            });
    }
}

module.exports = KujoMiva;
